﻿using FEShop.AppUserService.Configs;
using FEShop.AppUserService.Models;
using Microsoft.Extensions.Options;
using Microsoft.Identity.Client;
using SqlSugar;

namespace FEShop.AppUserService.Contexts
{
    /// <summary>
    /// AppUserDbContext
    /// </summary>
    public class AppUserDbContext
    {
        public SqlSugarScope Db { get; }
        private readonly IConfiguration _configuration;
        private readonly IOptions<AppUserConfig> _options;

        /// <summary>
        /// AppUserDbContext 构造函数
        /// </summary>
        /// <param name="config"></param>
        public AppUserDbContext(IConfiguration config)
        {
            _configuration = config;
            var connectionString = config.GetSection("ConnectionStrings:FullCtrlConnection").Value;
            Db = new SqlSugarScope(new ConnectionConfig()
            {
                DbType = SqlSugar.DbType.MySql,
                ConnectionString = connectionString,
                IsAutoCloseConnection = true
            });
        }

        /// <summary>
        /// 获取连接对象
        /// </summary>
        /// <returns></returns>
        public SqlSugarClient GetInstance()
        {
            var mysqlConn = GlobalConfig.Current.ConnectionStrings.MySqlConnection;
            return new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = mysqlConn,
                DbType = DbType.MySql,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });
        }

        /// <summary>
        /// 表结构初始化
        /// </summary>
        public void InitTabls()
        {
            Type[] types = new Type[]
            {
                typeof(AppUser),
                typeof(UserAddress),
                typeof(ShopCart),
                typeof(ShopCartItem)
            };
            try
            {
                //一次生成所有相关的表
                Console.WriteLine("===========================================================");
                var conn = _configuration.GetSection("ConnectionStrings:FullCtrlConnection").Value;
                Console.WriteLine($"连接字符串: {conn}");
                Db.CodeFirst.InitTablesWithAttr(types);
            }
            catch (Exception ex)
            {
                Console.WriteLine("-----------------------执行数据库表迁移出现异常：-----------------------");
                Console.WriteLine(ex.Message,ex);
            }
        }

    }
}
